#include <cardspot.h>
#include <assert.h>
#include <card.h>

#include "cardspot.h"

static inline bool removeOne(std::vector<Card*> &vector, Card *card)
{
    for (std::vector<Card*>::iterator it = vector.begin(); it != vector.end(); ++it) {
        if (*it == card) {
            vector.erase(it);
            return true;
        }
    }
    return false;
}


CardSpot::CardSpot(int type, const std::string &name)
    : RenderObject(Type_CardSpot, 255, 0, 0, 0), data(type, name)
{
}

const std::vector<Card*> &CardSpot::cards() const
{
    return data.cards;
}

bool CardSpot::drop(Card *card)
{
    assert(card);
    if (canDrop(card)) {
        if (card->cardSpot())
            ::removeOne(card->cardSpot()->data.cards, card); // assert if returns false?
        card->setCardSpot(this);
        data.cards.push_back(card);
        return true;
    }
    return false;
}

Card * CardSpot::pop()
{
    assert(data.cards.size() > 0);
    Card *card = data.cards.back();
    data.cards.pop_back();
    return card;
}

int CardSpot::indexOf(const Card *card) const
{
    int index = 0;
    for (std::vector<Card*>::const_iterator it = data.cards.begin(); it != data.cards.end(); ++it) {
        if (*it == card) {
            return index;
        }
        ++index;
    }
    return -1;
}
void CardSpot::push_back(Card *card)
{
    data.cards.push_back(card);
}

std::vector<Card*> CardSpot::cards(Card *from) const
{
    assert(from);
    const int index = indexOf(from);
    assert(index != -1);
    std::vector<Card*> result;
    for (std::vector<Card*>::const_iterator it = data.cards.begin() + index; it != data.cards.end(); ++it) {
        result.push_back(*it);
    }
    return result;
}
